package demo1;

import java.util.Arrays;
import java.util.Comparator;

class Student/* implements Comparable <Student>*/{
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    /*@Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }*/
}

//1.当代码重合率达到80%时用继承
//2.重合率达到50%用接口

/**
 * 接口的使用
 * 接口是特殊的抽象类
 * 所以当子类实现接口后，可以对子类进行实例化，且类型定义为接口
 * 以后使用时，我们可以直接利用子类实例化的接口来调用在子类重写的接口中的方法
 * 或者我们可以实例化子类对象来调用重写的接口的方法
 */
class AgeComparator implements Comparator <Student>{
    @Override
    public int compare(Student o1, Student o2) {
        return o1.getAge() - o2.getAge();
    }
}

class NameComparator implements Comparator <Student>{

    @Override
    public int compare(Student o1, Student o2) {
        /**
         * 如何理解这种写法
         * 1.String 类实现了 Comparable 这个接口
         *  所以证明 String 类里面已经重写了字符串比较的方法
         * 2.Student 类定义了成员变量String name
         *  理解为 String 类的实例 name 成为了成员变量
         * 3.String 类的实例当然可以访问 String 类里公开的比较方法 compareTo
         */
        return o1.getName().compareTo(o2.getName());
    }
}

public class Test {
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("hello",20);
        students[1] = new Student("wuxi",10);
        students[2] = new Student("dali",17);

        AgeComparator ageComparator = new AgeComparator();
        NameComparator nameComparator = new NameComparator();

        Arrays.sort(students,nameComparator);

        System.out.println(Arrays.toString(students));
    }

    public static void main1(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("hello",20);
        students[1] = new Student("wuxi",29);
        students[2] = new Student("dali",17);
        Arrays.sort(students);
        System.out.println(Arrays.toString(students));
    }

}
